package com.demo.validator;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import com.demo.mobile.DES;
import com.demo.mobile.MobileInfo;
import com.demo.service.MobileVerifyService;
import com.demo.util.ProtobufUtils;
import com.demo.util.SpringContextUtil;
import com.mdx.mobile.base.MRequest;


@Component
public class MobileLoginValidate implements LoginInterface{
	
	private MobileVerifyService mobileVerifyService=SpringContextUtil.getBean(MobileVerifyService.class);
	
	@Override
	public boolean isLogin(HttpServletRequest req) {
		Map<String, Object> param=null;
		try {
			param = getParam(req);
		} catch (Exception e) {
			return false;
		}
		if(param.get("deviceid")==null||param.get("verify")==null||param.get("userid")==null){
			return false;
		}
		String deviceId = param.get("deviceid").toString();
		String verify =  param.get("verify").toString();
		String userId = param.get("userid").toString();
		
		if(StringUtils.isBlank(deviceId)||StringUtils.isBlank(verify)||StringUtils.isBlank(userId)){
			return false;
		}
		return mobileVerifyService.findLogin(deviceId,verify,userId);
	}
	 
	private Map<String, Object> getParam(HttpServletRequest request) throws Exception {
		Map paramMap = new HashMap();
		for (Object paramName : request.getParameterMap().keySet()) {
			if (!StringUtils.isNotBlank((String) paramName)){
				continue;
			}
			String paramValue = request.getParameter((String) paramName);

			paramMap.put(paramName, paramValue);
		}

		try {
			byte[] protobuf = {};
//			if(request instanceof StandardMultipartHttpServletRequest){
//				protobuf = StreamUtils.copyToByteArray(((StandardMultipartHttpServletRequest)request).getRequest().getInputStream());
////				MultipartFile f = ((StandardMultipartHttpServletRequest)request).getFile("file");
////				protobuf = f.getBytes();
//			}else{
//				protobuf = StreamUtils.copyToByteArray(request.getInputStream());
//			}
			protobuf = StreamUtils.copyToByteArray(request.getInputStream());
			MRequest.Msg_Request.Builder requestProtobuf = (MRequest.Msg_Request.Builder) ProtobufUtils.deserialize(
					new DES().desDecrypt(protobuf), MRequest.Msg_Request.class);

			for (int i = 0; i < requestProtobuf.getPostsCount(); i++) {
				paramMap.put(requestProtobuf.getPosts(i).getName(), requestProtobuf.getPosts(i).getValue());
			}
 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		MobileInfo mobileInfo = new MobileInfo((String) paramMap.get("userid"), (String) paramMap.get("deviceid"),
				(String) paramMap.get("appid"),(String) paramMap.get("areaCode"));
		paramMap.put("mobileInfo", mobileInfo);
		return paramMap;
	}
	
}
